package com.gongyou.forum.controller;

import com.alibaba.fastjson.JSONObject;
import com.gongyou.common.constant.UserConstant;
import com.gongyou.common.entity.Result;
import com.gongyou.common.pojo.User;
import com.gongyou.common.utils.JwtUtil;
import com.gongyou.common.utils.SendMessageUtils;
import com.gongyou.common.utils.ValidateCodeUtils;
import com.gongyou.forum.service.UserLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author LiQuanPing
 * @Date 2021-03-19 15:14
 * @Version 1.8
 * @creed: ♂♂Talk is cheap,show me the code♀♀
 * <p>
 * 用户登陆,注册,忘记密码 处理controller
 */
@Slf4j
@RestController
@RequestMapping("/userLogin")
public class UserLoginController {


   // @Value("${wechat.appid}")
    private String appid = "你的id";
   // @Value("${wechat.appsecret}")
    private String appsecret = "你的密码";

    private String openid;
    private String session_key;

    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //用户手机号码登录
    @RequestMapping("/login")
    public Result userLogin(@RequestBody User user) {
        log.info("电话是" + user.getPhone() + ";密码是" + user.getPassword());
        String phone = user.getPhone();
        User user1 = userLoginService.login(user);
        if (user1 != null) {
            boolean checkpw = BCrypt.checkpw(user.getPassword(), user1.getPassword());
            if (checkpw) {
                //密码匹配成功
                String jwt = JwtUtil.createJWT(phone, phone, null);
                Map map = new HashMap();
                map.put("userId", user1.getId());
                map.put("phone", user1.getPhone());
                map.put("gender", user1.getGender());
                map.put("avatarUrl", user1.getAvatarUrl());
                map.put("username", user1.getNickName());
                map.put("token", jwt);
                return new Result(true, UserConstant.USER_LOGIN_FULL, map);
            } else {
                return new Result(false, UserConstant.USER_NAME_ERROR);
            }
        } else {
            return new Result(false, UserConstant.USER_NAME_ERROR);
        }

    }

    //用户手机号码注册
    @RequestMapping("/register/{code}")
    public Result register(@RequestBody User user, @PathVariable("code") String code) {
        // System.out.println("电话是"+user.getPhone()+";密码是"+user.getPassword());
        String phone = user.getPhone();
        String redisCode = stringRedisTemplate.opsForValue().get(phone + "reg");
        if (redisCode != null && redisCode.equals(code)) {
            try {
                userLoginService.register(user);
                return new Result(true, "注册成功");
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, "网络超时，请重试");
            }
        } else {
            return new Result(false, "验证码错误");
        }
    }

    //根据手机号码判断用户是否注册
    @RequestMapping("/phoneIsReg")
    public boolean phoneIsReg(String phone) {
        return userLoginService.phoneIsReg(phone);

    }

    //发送注册验证码
    @RequestMapping("/sendRegCode")
    public Result sendRegCode(String phone) {
        String code = ValidateCodeUtils.generateValidateCode(6);
        try {
            SendMessageUtils.sendMessage(phone, 930085, code);
            stringRedisTemplate.opsForValue().set(phone + "reg", code, 5, TimeUnit.MINUTES);
            return new Result(true, "验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "验证码发送失败");
        }
    }

    //发送忘记密码验证码
    @RequestMapping("/sendForgetPassword")
    public Result sendForgetPassword(String phone) {
        String code = ValidateCodeUtils.generateValidateCode(6);
        try {
            SendMessageUtils.sendMessage(phone, 929312, code);
            stringRedisTemplate.opsForValue().set(phone + "forget", code, 5, TimeUnit.MINUTES);
            return new Result(true, "验证码发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "验证码发送失败");
        }
    }


    //根据电话号码修改密码
    @RequestMapping("/editPassword/{code}")
    public Result editPasswordByPhone(@RequestBody User user, @PathVariable("code") String code) {
        String phone = user.getPhone();
        String redisCode = stringRedisTemplate.opsForValue().get(phone + "forget");
        //判断验证码是否有效和正确
        if (redisCode != null && redisCode.equals(code)) {
            try {
                userLoginService.editPasswordByPhone(user);
                return new Result(true, "密码修改成功");
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, "网络超时，请重试");
            }
        } else {
            return new Result(false, "验证码错误");
        }
    }

    //测试微信登录
    @GetMapping("/weChatLogin")
    public String weChatLogin(String code) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appsecret + "&js_code=" + code + "&grant_type=authorization_code";
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 解析json
        JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
        session_key = jsonObject.get("session_key") + "";
        openid = jsonObject.get("openid") + "";

        System.out.println("session_key==" + session_key);
        System.out.println("openid==" + openid);
        return resultString;

    }
}


